# The directories containing the source files, separated by ':'
VPATH=.

# Your final binary
TARGET=compiler

# default target (when not specifying)
DEFAULT=debug

# What include flags to pass to the compiler
INCLUDEFLAGS= 

# A common link flag for all configurations
LDFLAGS += -L../Common/anyoption -lanyoption

############################################################################
############################################################################
############################################################################

SRC = $(wildcard *.cpp)

ifeq ($(CFG),)
CFG=$(DEFAULT)
endif

# Build a Dependency list and an Object list, by replacing the .cpp
# extension to .d for dependency files, and .o for object files.
DEP = $(patsubst %.cpp, $(CFG)/deps/%.d, ${SRC})
OBJ = $(patsubst %.cpp, $(CFG)/objs/%.o, ${SRC})

# What compiler to use for generating dependencies: 
# it will be invoked with -MM -MP
CXXDEP = g++

# Separate compile options per configuration
ifeq ($(CFG),debug)
CXXFLAGS += -ggdb -Wall -D_DEBUG ${INCLUDEFLAGS}
else
CXXFLAGS += -O2 -Wall ${INCLUDEFLAGS}
endif


all: inform $(CFG)/${TARGET}

inform:
	@echo "Configuration "$(CFG)
	@echo "------------------------"

$(CFG)/${TARGET}: ${OBJ} 
	@mkdir -p $(dir $@)
	@echo "Linking..."
	@$(CXX) -g -o $@ $^ ${LDFLAGS}

$(CFG)/objs/%.o: %.cpp | inform
	@mkdir -p $(dir $@)
	$(info Compiling $<)
	@$(CXX) -c $(CXXFLAGS) -o $@ $<

$(CFG)/deps/%.d: %.cpp
	@mkdir -p $(dir $@)
#@echo Generating dependencies for $<
	@set -e ; $(CXXDEP) -MM -MP $(INCLUDEFLAGS) $< > $@.$$$$; \
	sed 's,\($*\)\.o[ :]*,$(CFG)\/objs\/\1.o $@ : ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$

clean:
	@rm -rf debug release

# Unless "make clean" is called, include the dependency files
# which are auto-generated. Don't fail if they are missing
# (-include), since they will be missing in the first invocation!
ifneq ($(MAKECMDGOALS),clean)
-include ${DEP}
endif

